<template>
    <view class="content">
        <view class="main">
            <van-nav-bar :title="scrolling ? navBarTitle : ''" left-arrow @click-left="onClickLeft" id="navBar">
                <view class="topCartIcon" slot="right" :style="cartRight" @click="toMyCart"><van-icon name="cart-o"  class="cartIcon" /> </view>
            </van-nav-bar>
            <!-- <van-nav-bar :title="title" left-arrow @click-left="onClickLeft" style="z-index:104; background-color: #ffffff;"> </van-nav-bar> -->
            <!--滚动内容区域-->
            <scroll-view class="scroll-content" @scrolltolower="scrolltolower" @scroll="scrollPage" scroll-y
                show-scrollbar="false">
                <!-- <loading :loadingIsShow="loadingIsShow" v-if="!isrefresher"></loading> -->
                <!-- <view class="scroll-card"> -->
                <!-- <template v-if="pageSign!='coupon'">
                        <view class="top_box" :class="{ fixed_top: scrolling }">
                            <view class="titleDiv" v-if="!scrolling">
                                <view class="tableTitle"> 单笔实付满{{ fullDiscount.full }}减{{fullDiscount.reduction}} </view>
                                <view class="titleDate">{{ titleDate }}</view>
                            </view>
                            <view class="tableBox_top" id="tableBox_top" >
                                <view class="tableBox_top_item" @click="showJoinPopup(0)">{{sortName}} <van-icon name="arrow-down" size="12" style="margin-left: 12rpx;" /> </view>
                                <view class="tableBox_top_item" @click="showJoinPopup(1)">{{allTypes}} <van-icon name="arrow-down" size="12" style="margin-left: 12rpx;" /> </view>
                                <view class="tableBox_top_item" @click="showJoinPopup(2)">{{priceRange}} <van-icon name="arrow-down"  size="12" style="margin-left: 12rpx;" /> </view>
                            </view>
                        </view>
                    </template> -->
                <template v-if="pageSign!='coupon'">
                    <view class="top_box">
                        <view class="titleDiv">
                            <view class="tableTitle"> 单笔实付满{{ fullDiscount.full }}减{{fullDiscount.reduction}} </view>
                            <view class="titleDate">{{ titleDate }}</view>
                        </view>
                    </view>
                </template>
                <template v-else>
                    <view class="top_box">
                        <view class="titleDiv">
                            <view class="tableTitle"> {{tableTitle}}</view>
                            <view class="titleDate">{{ titleDate }}</view>
                        </view>
                    </view>
                </template>
                <!--  :class="{ scroll_box: scrolling }" -->
                <view class="joinGoodsBox ">
                    <view class="goodsListBox">
                        <view class="joinGoodsList" v-for="(itemL, indexL) in joinGoodsList" :id="indexL" :key="indexL"
                            @click="toGoodsDetail(itemL, indexL)">
                            <view class="joinGoods_img">
                                <img :src="itemL.image" alt="">
                                <view class="status_tips" v-if="itemL.stock==0">已售罄</view>
                            </view>
                            <view class="joinGoods_subtitle pl15">{{ itemL.storeSubtitle }}</view>
                            <view class="joinGoods_title pl15">{{ itemL.storeName }}</view>
                            <view class="joinGoods_bottom">
                                <view class="joinGoods_price pl15">￥{{ itemL.price }}</view>
                                <view class="productsCardCartIcon" v-if="pageSign!='coupon'"
                                    @click.stop="openSpecsPopup(itemL,indexL)"><van-icon name="cart-o"
                                        class="cartIcon" /></view>
                            </view>
                        </view>
                    </view>
                </view>
            </scroll-view>
        </view>
        <!-- 规格选择 -->
        <specsPopup :showSpecsPopup="showSpecsPopup" :buttonStatus="buttonStatus" @closeSpecsPopup="closeSpecsPopup"
            :parentSign="parentSign" :ebProductAttr="specsList" :ebStoreProduct="ebStoreProduct"
            :ebStoreProductAttrValue="specsPriceList" :selectedIds="selectedIds" :selectSuk="selectSuk"
            :biaozhi="params.biaozhi" @submitBuy="submitBuy"> </specsPopup>

        <!-- 商品排序 -->
        <joSortPopup :JOpopup="joSortpopup" :popupBiaoshi="popupBiaoshi" @closeJOPopup="closeJOSortPopup"
            @closeJOPricePopup="closeJOPricePopup"></joSortPopup>
        <!-- 全部分类 -->
        <joinOrdersPopup :JOpopup="JOpopup" :popupBiaoshi="popupBiaoshi" @closeJOPopup="closeJOPopup"></joinOrdersPopup>
    </view>
</template>

<script>
import joinOrdersPopup from '@/mycomponents/shangcheng/joinOrderPopup.vue'
import joSortPopup from '@/mycomponents/shangcheng/joSortPopup.vue';
// import loading from '@/mycomponents/loading.vue'
import {getProductListApi,getLeFullDiscountProductGetAddProductApi} from '@/api/mall'
import specsPopup from '@/mycomponents/specsPopup.vue'
import { queryProductByIdApi } from '@/api/mall'
import { SOURCE_TYPE } from '@/utils/constant'
import {getShoppingCartSizeApi} from '@/api/shoppingCart'


export default {
    components: {
        joinOrdersPopup,
        joSortPopup,
        // loading,
        specsPopup
    },
    data () {
        return {
            isrefresher: false,
            loadingIsShow: true,
            loadingIsShowPage: true,
            name: '凑单',
            scrolling: false, // 顶部区域吸顶效果
            scrollMT: '',
            listTop:0,
            joSortpopup:false, //商品排序弹窗
            JOpopup:false,
            popupBiaoshi:0,
            // isrefresher: false,
            tableList: [],
            pageSign:'joinOrder', //页面标识  joinOrder 凑单  coupon 优惠券  cart 购物车底部凑单
            tableTitle: '单笔实付满300减20',
            title:'',
            titleDate:"12月30日  23:59前可享",
            sortName:'综合排序',
            allTypes:'全部分类',
            priceRange:'价格区间',
            joinGoodsList: [], //商品列表
            cateId:undefined,
            isNew:undefined,   //是否新品
            sortField:undefined,   //排序字段
            isHot:undefined,  //热卖
            maxPrice:undefined,
            minPrice:undefined,
            params:{},
            totalAdditionalAmount:undefined, //总凑金额
            totalThresholdAmount:undefined, //总满减金额
            fullDiscount:undefined,  // 最佳满减规则 \/ 满减规则
            productIds:undefined,  //商品ids 优惠券对应的可使用的商品id
            apiParams:{},
            fullDiscountId:undefined,  // 满减id
            useType:undefined,  // 满减使用类型
            discountApply:undefined,  //满减应用（1：电商，2：服务）
            type:undefined,  // 优惠券对应的商品类型

            showSpecsPopup: false, // 规格弹窗
            buttonStatus: 1, // 点击加入购物车 或者 立即购买  传入的按钮内容标志
            productId: '', // 商品id
            ebStoreProduct: {}, // 商品详情
            specsList: [], // 规格
            specsPriceList: [], // 规格价格
            selectedIds: [], // 已选规格
            selectSuk: '', // 已选规格组合名

            menuButtonTop: '',
            menuButtonWidth: '',
            cartRight: '', // 购物车距离右边距离
            titleTop: '',

        }
    },
    onLoad (data) {
        const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
        console.log('胶囊按钮高度：', menuButtonInfo.height)
        console.log('胶囊按钮top：', menuButtonInfo.top, menuButtonInfo)
        console.log('胶囊按钮宽度：', menuButtonInfo.width)
        this.menuButtonWidth = menuButtonInfo.width
        this.cartRight = 'margin-right:' + (this.menuButtonWidth + 0) + 'px'
        console.log(this.cartRight,'this.cartRight')
        this.menuButtonTop = menuButtonInfo.top
        // this.titleTop = 'margin-top:' + (this.menuButtonTop + menuButtonInfo.height / 3) + 'px'
        this.titleTop = 'margin-top:' + (this.menuButtonTop + (menuButtonInfo.height - 25) / 2) + 'px'
        console.log(this.titleTop)

        if(data&& data.params){
        	this.params = JSON.parse(decodeURIComponent(data.params)) || {}
            console.log(this.params,'this.params')
            // if(this.params.pageSign != 'coupon'){
            //     let query = wx.createSelectorQuery()
            //     //需要给黄色区域设置一个id标识，在这里是demo
            //     query.select('#tableBox_top').boundingClientRect(data => {
            //         console.log(data.top, 'data.top', data)//这个就是距离顶部的高度
            //         this.listTop = data.top//赋值，待会要用
            //     }).exec();
            // }
            this.totalAdditionalAmount=this.params.totalAdditionalAmount
            this.totalThresholdAmount=this.params.totalThresholdAmount
            this.fullDiscount=this.params?.bestFullDiscount || null
            this.pageSign=this.params.pageSign || ''
             if (this.pageSign === 'coupon') {
                this.titleDate=this.params.titleDate
                this.tableTitle = (this.params.useType == 1 ? '全场通用券' : 
                  this.params.useType == 2 ? '商品券' : 
                  '品类券') + (this.params.item?.name ? '  ' + this.params.item.name : '')  

                this.productIds = this.params.item.productIds ? this.params.item.productIds.join(',') : undefined
                console.log(this.productIds,'this.productIds',this.tableTitle,this.params.item.name)
                if(this.params.item.productIds && this.params.item.productIds.length>0){
                	this.apiParams = { productIds:this.productIds, type:'new_product'}
                }else{
                	this.apiParams = { type:'new_product'}
                }
                
             }else{
                this.fullDiscountId=this.params.fullDiscountItem.id
                this.fullDiscount=this.params.fullDiscountItem
                this.titleDate=this.params.fullDiscountItem.deadline
                this.useType=this.params.fullDiscountItem.useType
                this.discountApply = this.params.fullDiscountItem.discountApply
             }
        }

    },
    onReady () {
        this.onRefresherMethod()

    },
    methods: {
        refresherpulling () {
            if (!this.isrefresher) {
                this.isrefresher = true // 下拉加载，先让其变true再变false才能关闭
                this.onRefresherMethod()
            }
        },
        onRefresherMethod() {
            if (!this.isrefresher) {
                this.loadingIsShow = true
            }
            // this.loadingIsShow = false
            // // 关闭加载状态 (转动的圈)，需要一点延时才能关闭
            // this.time = setTimeout(e => {
            //     this.isrefresher = false
            // }, 300)
            let productList = null
            let productIdsList = null
            let apiList = []
            if (this.pageSign === 'coupon') {
            	productList = this.getProductList()
                apiList = [productList]
            }else {
                if (this.useType == 1){
                    this.apiParams = { type:'new_product'}
                    productList = this.getProductList()
                    apiList = [productList]
                }else{
                    // 先获取productIds，再获取商品列表（链式调用）
                    const productFlow = this.getLeFullDiscountProductGetAddProductList()
                        .then(() => {
                            // 更新apiParams后调用商品列表接口
                            this.apiParams = { productIds: this.productIds, type: 'new_product' };
                            return this.getProductList(); // 返回商品列表的Promise
                        });
                    apiList = [productFlow]; // 将完整流程的Promise加入列表
                    // productIdsList = this.getLeFullDiscountProductGetAddProductList()
                    // this.apiParams = { productIds:this.productIds, type:'new_product'}
                    // console.log(this.apiParams,'this.apiParams')
                    // // productList = this.getProductList()
                    // apiList = [productIdsList]
                }
            }

            Promise.all(apiList).then(() => {
                console.log('所有api加载完成')
                // if (this.pageSign !== 'coupon' && this.useType !== 1) {
                // 	this.getProductList()
                // }
                this.loadingIsShow = false
                // 关闭加载状态 (转动的圈)，需要一点延时才能关闭
                this.time = setTimeout(e => {
                    this.isrefresher = false
                }, 300)
            })
        },
        scrolltolower () {

        },

        scrollPage (e) {
            console.log(e.detail.scrollTop, this.scrolling)
            if (e.detail.scrollTop > 60 && !this.scrolling) {
				this.scrolling = true
			} else if (e.detail.scrollTop <= 60 && this.scrolling) {
				this.scrolling = false
			}
            // this.bgOpacity = `opacity:${1 - e.detail.scrollTop / this.navHeight}`
        },
        onClickLeft () {
            uni.navigateBack()
        },
        // 商品详情
        toGoodsDetail(item, index){
            const params={
             item:item,
             productId:item.id,
             biaozhi:this.pageSign
            }

            uni.navigateTo({ url: '/pages/shangcheng/goodsDetail?params=' + encodeURIComponent(JSON.stringify(params)) })
        },

        // 去我的购物车
        toMyCart () {
            // authMixin()
            const params = {}
            uni.navigateTo({
                url:
              '/pages/shoppingCart/gouwuche?params=' +
              encodeURIComponent(JSON.stringify(params))
            })
        },

        // 弹窗
        showJoinPopup(val){
            console.log(val,'val')
            if(val===1){  //全部分类  是另一个弹窗
                this.JOpopup=true
            }else{  //综合  价格  是同一个弹窗
                this.joSortpopup=true
            }
          
            this.popupBiaoshi=val
        },

        closeJoinPopup(val){
            this.JOpopup=false
            this.popupBiaoshi=val
        
        },
        //点击购物车按钮 加入到购物车 打开规格弹窗
        async openSpecsPopup (item, index) {
        	if(item.stock == 0){
        		uni.showToast({
        			title:'商品已售罄',
        			icon:'none'
        		})
        		return
        	}
            try {
                // 先获取数据再打开弹窗
                await this.queryProductByIdApiMethod(item.id);
                // 数据就绪后再设置弹窗可见
                this.$nextTick(() => {
                    this.productId = item.id //接口需要id
                    this.selectSuk = item.productSkuName;
                    this.cartProInfo = item
                    this.showSpecsPopup = true;
                });
            } catch (error) {
                Toast('商品数据加载失败');
            }
        },
        // 关闭规格弹窗
        closeSpecsPopup (result) {
            this.showSpecsPopup = false
            if(result === 'success'){
                this.getCartNumMethod()
            }
        },

        // 关闭弹窗  全部分类  
        closeJOPopup(){
            this.JOpopup=false
        },

         // 关闭弹窗  商品排序
        closeJOSortPopup(index,item,popupBiaoshi){
            this.joSortpopup=false
            this.sortName=item
            if (popupBiaoshi === 0) {
                if (item.includes('综合') || index === 0) {
                    this.sortField = 'goodReviewRate'
                } else if (item.includes('销量') || index === 1) {
                    this.sortField = 'sales  desc'
                } else if (index === 2) {  //价格降序
                    this.sortField = "price desc"
                } else if (index === 3) { //价格降序
                    this.sortField = "price asc"
                } else if (item.includes('新品') || index === 4) {
                    this.sortField = undefined
                    this.isNew = true
                }
            }
           
            this.getProductList()
        },
        closeJOPricePopup(minPrice,maxPrice){
            this.joSortpopup=false
            this.cateId=undefined,
            this.isNew=undefined,   //是否新品
            this.sortField=undefined,   //排序字段
            this.isHot=undefined,  //热卖

            this.maxPrice=maxPrice
            this.minPrice=minPrice
           
            this.getProductList()
        },

        // 接口  商品列表
        getProductList() {
            return new Promise((resolve, reject) => {
                //NEW_PRODUCT 新品
                //HOT_PRODUCT 热卖
                //SURPRISE 惊喜
                //BEST_PRODUCT 好评如潮
                getProductListApi(this.apiParams).then((res) => {
                    console.log(res.data)
                    if (res.code === 200) {
                        this.joinGoodsList = res.data.list
                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
            })
        },
        getLeFullDiscountProductGetAddProductList(){
            return new Promise((resolve, reject) => {
                getLeFullDiscountProductGetAddProductApi({fullDiscountId:this.fullDiscountId}).then((res) => {
                    console.log(res.data)
                    if (res.code === 200) {
                        console.log(res.data)
                        if(res.data){
                            console.log(res.data)
                            this.productIds = res.data.join(',')
                            this.apiParams = { productIds:this.productIds, type:'new_product'}
                        }
                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
            })
        },

        // 商品信息
        queryProductByIdApiMethod (productId) {
            return new Promise((resolve, reject) => {
                queryProductByIdApi({id: productId}).then((res) => {
                    console.log(res)
                    if (res.code === 200) {
                        console.log('res-----', res.data)
                        this.ebStoreProduct = res.data?.ebStoreProduct // 轮播图  名称  价格等
                        this.specsList = res.data?.ebProductAttr
                        // this.ebStoreProductAttrRelationDTO=res.data.ebStoreProductAttrRelationDTO
                        this.specsPriceList=res.data.ebStoreProductAttrValue   //规格组合对应的价格

                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
            })
        },
        // 购物车列表
        getCartNumMethod(){
            return new Promise((resolve, reject) => {
                getShoppingCartSizeApi().then((res)=>{
                    console.log(res,'res')
                    if(res.code===200){
                       this.myCartNum = res.data 
                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
            })
        },

    }
}
</script>

<style lang="scss" scoped>
.content {
    height: 100vh;
    overflow: hidden;
    background-color: #ffffff;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
	z-index: -3;

}

.main {
    position: relative;
	display: flex;
	flex-direction: column;
	box-sizing: border-box;
	height: 100vh;
	background-color: #ffffff;

    .fixed_top {
        position: fixed;
        width: calc(100% - 96rpx);
        z-index: 104;  //与页面的navbar同级
        // top: 85rpx;
    }
    .scroll_box{
        position: absolute;
        top: 107px;
        z-index: 1;
    }
}



::v-deep .van-nav-bar {
    background-color: #ffffff !important;
    z-index: 100 !important;
}

::v-deep .van-nav-bar__arrow {
    color: #111111 !important;
}

::v-deep .van-icon {
    color: #111111 !important;
}



.scroll-content {
    flex: 1;
    height: 1rpx;
}
// .scroll-content-box{
//     flex: 1;
//     height: 1rpx;
// }

.backIcon {
    margin-top: 16rpx;
}

.scroll-card {
    padding: 0 48rpx 96rpx;

}

.top_box{
    padding-left: 48rpx;
    padding-right: 48rpx;
    background: #ffffff;
}

.topCartIcon{
    width: 19px;
    height: 19px;
    background-color: rgb(0, 0, 0, 0.2);
    padding: 3px;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}
// 名称+日期
.titleDiv{
    
    .tableTitle{
        // font-weight: bold;
        font-size: 52rpx;
        line-height: 52rpx;
        text-align: left;
        color: #111111;
    }
    .titleDate{
        // font-weight: bold;
        font-size:20rpx;
        text-align: left;
        color: #A6A6A6;
        line-height: 20rpx;
        margin-top: 30rpx;
        margin-bottom: 40rpx;
    }

}


// 固定区域
.tableBox_top{
    background: #ffffff;
    // padding-top: 29rpx;
    display: flex;
    justify-content: space-between;
    padding-top: 10px;
    padding-bottom: 12px;
}
.tableBox_top_item{
    font-size:28rpx;
    text-align: left;
    color: #111111;
    line-height: 28rpx;
}

.joinGoodsBox{
    // width: calc(100% - 96rpx);
    width: 100%;
    padding-left: 48rpx;
    padding-right: 48rpx;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    // z-index: -1;

}
.goodsListBox{    
    width: 100%;
    display: flex;
    justify-content: space-between;
    // justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    padding-bottom: 40px;
    /* 允许Flex项目换行 */
    // background: palegoldenrod;
}

.productList_content {}

.joinGoodsList {
    // width: 46%;
    width: 320rpx;
    // flex: 0 0 calc((100% - 48rpx) / 2);
    // flex: auto;
    // 盒子整体 距下一个20rpx、  原来是10 
    // margin-bottom: 40rpx;
    margin-bottom: 20px;
    box-shadow: 1rpx 1rpx 5rpx 0 rgb(231, 231, 231, 0.29);
    // margin-right: 30rpx;
    background: #ffffff;

.joinGoods_img {
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 320rpx;
    height: 320rpx;
    overflow: hidden;

    img {
    // width: 100%;
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
}
.status_tips {
    position: absolute;
    height: 108rpx;
    width: 100%;
    background: rgb(240, 240, 240, 0.66);
    align-items: center;
    text-align: center;
    line-height: 108rpx;
    font-size: 28rpx;
    text-align: center;
    color: #666666;
    // bottom: 10rpx;
    bottom:0rpx;
}

.joinGoods_subtitle {
    // max-width: 156rpx;
    // white-space: pre-wrap;  //换行  样式会出问题

    max-width: 100%;
    white-space: nowrap;
    /* 防止文本换行 */
    overflow: hidden;
    /* 超出部分隐藏 */
    text-overflow: ellipsis;
    
    // font-weight: 400;
    font-size: 20rpx;
    // line-height: 20rpx;
    text-align: left;
    color: #666666;
    margin-top: 28rpx;
    margin-left: 28rpx;
}

.joinGoods_title {
    // max-width: 156rpx;
    // white-space: pre-wrap;

    max-width: 100%;
    white-space: nowrap;
    /* 防止文本换行 */
    overflow: hidden;
    /* 超出部分隐藏 */
    text-overflow: ellipsis;
    /* 显示省略号 */
    // font-weight: bold;
    font-size: 28rpx;
    // line-height: 28rpx;
    text-align: left;
    color: #111111;
    margin-top: 22rpx;
    // margin-left: 22rpx;
    margin-left: 28rpx;
}
.joinGoods_bottom {
	display: flex;
    align-items: center;
    justify-content: space-between;
    // margin-top: 20rpx;
    // margin-left: 28rpx;
    // margin-right: 24rpx;
    // margin-bottom: 26rpx;
    margin: 20rpx 24rpx 26rpx 28rpx;
}

.joinGoods_price {
    // font-weight: 900;
    font-weight: bolder;
    line-height: 32rpx;
    font-size: 32rpx;
    text-align: left;
    color: #111111;
    // margin-top: 22rpx;
    // margin-bottom: 26rpx;
    // margin-left: 28rpx;
}

.productsCardCartIcon{
    width:30rpx;
    height:30rpx;
    background-color: #ff6203;
    padding: 3px;
    border-radius: 8rpx;
    display: flex;
    justify-content: center;
    align-items: center
}

}

.joinGoodsList:nth-child(2n) {
    margin-right: 0;
}

::v-deep .productsCardCartIcon .van-icon {
    color: #ffffff!important;
    font-size: 32rpx;
}
::v-deep .topCartIcon .van-icon {
    color: #ffffff!important;
    font-size: 38rpx;
}

</style>
